package com.xxx.springboot.interceptor;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import com.xxx.springboot.exception.BaseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 异常统一处理器（防止将异常信息透传给客户端）
 */
@Component
public class ExceptionResolver implements HandlerExceptionResolver {

	private static final Logger logger = LoggerFactory.getLogger(ExceptionResolver.class);
	
	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception e) {
		logger.error("{} happend exception: ", request.getRequestURI(), e);
		int code = 0;
		String msg = "";
		if(e instanceof BaseException) { // 自定义异常
			code = ((BaseException) e).getCode();
			msg = ((BaseException) e).getMsg();
		} else if (e instanceof NotLoginException) { // sa-token未登录异常
			code = 401;
			msg = "未登录";
		} else if (e instanceof NotPermissionException) { // sa-token没有权限异常
			code = 403;
			msg = "无权限";
		} else { // 非自定义异常
			code = 500;
			msg = "server exception";
		}
		ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
		modelAndView.addObject("code", code);
		modelAndView.addObject("msg", msg);
		return modelAndView;
	}

}
